var rootPath = getRootPath();

$(function() {

	$.ajax({
		url : rootPath + '/category/pid/0', // 父级pid都为0
		type : 'GET',
		success : function(data) {
			if(data.returnCode == "0000") {
				var length = data.returnObject.length;
				$("#selectPid").html(length);
				var option = "";
					option +="<option value = \"0\">分类类别</option>"
				for (var i = 0; i < length; i++) {
					option +="<option value =\""+data.returnObject[i].categoryId +"\">" +data.returnObject[i].title +"</option>";
				}
				$("#selectPid").append(option);
			}else {
				layer.alert(data.returnMessage);
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
			layer.alert("error:(");
		}
	});
	
	
	$("#categoryAddForm").validate({
		rules : {
			title : {
				required : true,
				remote : {
					type : "GET",
					url : rootPath + "/category/checkCategoryTitle",
					data : {
						title : function() {
							return $("#title").val();
						}
					},
					dataFilter : function(data,type) {
						if(data == "true") {
							return true;
						} else {
							return false;
						}
					}
				}
			}
		},
		messages: {
			title:{
				remote : "类别已存在"
			}
		},
		onkeyup:false,
		focusCleanup:true,
		success:"valid",
		submitHandler:function(form){
			$.ajax({
				url: rootPath + '/category'+ $('#categoryAddForm').val(),
	            type: 'POST',
	            data: JSON.stringify($('#categoryAddForm').serializeJson()),
	            contentType: 'application/json;charset=UTF-8',
	            success: function (data) {
	            	if("0000" == data.returnCode) {
	            		layer.msg('添加成功!',{icon:1,time:1000},function() {
	            			parent.window.location.href = rootPath + '/categoryPage';
	            			var index = parent.layer.getFrameIndex(window.name);
	            			parent.$('.btn-refresh').click();
	            			parent.layer.close(index);
	            		});
	            	} else {
	            		layer.alert(data.returnMessage);
	            	}
	            },
	            error: function (jqXHR, textStatus, errorThrown) {
	            	layer.msg('error!',{icon:1,time:1000});
	            }
	        });
		}
	});
});